package com.zp.self.module.level_5_设计模式.结构型模式.Ⅰ_代理模式.动态代理_CGLB;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author ：by Zeng Peng
 * @date ：Created 2022/6/27 21:34
 * @description ：CGLB动态代理工厂
 */
public class ProxyFactory {

    public  static <T> T getProxyInstance(Class<T> target){
        try {
            T instance = target.getDeclaredConstructor().newInstance();
            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(target);
            enhancer.setCallback(new MethodInterceptor() {
                @Override
                public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                    System.out.println("CGLB 收取手续费10块");
                    return method.invoke(instance, objects);
                }
            });
            return (T)enhancer.create();
        } catch (Exception e) {
            throw new RuntimeException("构建异常",e);
        }
    }
}
